<?php
$action = $_GET["action"];
if ($action == "deleteRequest") {
        $fid = $_GET["fid"];
        MakeFriend_Controller::delete_request($fid);
}elseif($action == "confirmRequest"){
        $fid = $_GET["fid"];
        $whoami = $_GET["ownid"];
        $friendid = $_GET["friendid"];
        MakeFriend_Controller::confirm_request($fid,$whoami,$friendid); 
}elseif($action == "changeGroup"){
		$fid = $_GET["fid"];
		$grpid = $_GET["grpid"];
		$grpname = $_GET["grpname"];
		MakeFriend_Controller::change_grp($fid,$grpid,$grpname);
}elseif($action == "deleteFriend"){
		$fid = $_GET["fid"];
		$ownid = $_GET["ownid"];
		$friendid =	$_GET["friendid"];
		MakeFriend_Controller::del_friend($fid,$ownid,$friendid);
}elseif($action == "addGrp"){
		$whoami = $_GET['id'];
		$grpname = $_GET["grpname"];
		MakeFriend_Controller::addGroup($whoami, 0, $grpname);
}elseif($action == "delGrp"){
		$ownid = $_GET['id'];
		$grpid = $_GET['grpid'];
		$grpname = $_GET['grpname'];
		MakeFriend_Controller::delGrp($ownid,$grpid,$grpname);
}
Class MakeFriend_Controller {
		function checkUser($id){
			require('../host_config.php');
            require_once('../Model/MySQL.php');
            $mysql = new MySQL();
            $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
            $id = mysql_real_escape_string($id);
            $sql = "SELECT active_flag FROM user WHERE uid = '$id'";
            $row = mysql_query($sql, $link);
            $check = null;
            while($rows = mysql_fetch_row($row)){$check = $rows[0];}
            if($check==2){
            	return 2;
            }elseif($check==1){
            	return 1;
            }else{
            	return 0;
            }
		} 
        function addFriend($whoami, $id, $groupName, $isCheck){
        	require('../host_config.php');
            require_once('../Model/MySQL.php');
            $mysql = new MySQL();
            $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
            $whoami = mysql_real_escape_string($whoami);
            $id = mysql_real_escape_string($id);
            $groupName = mysql_real_escape_string($groupName);
            $isCheck = mysql_real_escape_string($isCheck);
            $sql_max = "SELECT group_id, group_name FROM friendlist WHERE owner_id = '$whoami' ORDER BY group_id ASC";
            $row_max = mysql_query($sql_max, $link) or die(mysql_error());
            while($result_max=mysql_fetch_row($row_max)){
            	$group_id=$result_max[0];
                $group_name=$result_max[1];
            }               
            if($group_id==NULL){
                $group_id=1;
                $group_name=$groupName;
            }elseif($groupName==$group_name){
            }else{
                $group_id=$group_id+1;
                $group_name=$groupName;
            }
            MakeFriend_Controller::addGroup($whoami, 0, $groupName);
            $sql = "INSERT INTO `friendlist`(`owner_id` ,`friend_id` ,`group_id` ,`group_name` ,`Ischeck`) VALUES ('$whoami', '$id', '$group_id', '$groupName', '$isCheck')";
            mysql_query($sql, $link);
        }
        function del_friend($fid,$ownid,$friendid){
        	require("../host_config.php");
        	require_once("../Model/MySQL.php");
        	$mysql = new MySQL();
        	$link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
        	$fid = mysql_real_escape_string($fid);
        	$ownid = mysql_real_escape_string($ownid);
        	$friendid = mysql_real_escape_string($friendid);
        	//正向關係刪除
			$sql = "DELETE FROM friendlist WHERE fid = '$fid'";
			mysql_query($sql, $link);
			//反向關係刪除
			$sql_find_fid = "SELECT fid from friendlist WHERE owner_id = '$friendid' and friend_id = '$ownid'";
			$row_find_fid = mysql_query($sql_find_fid, $link) or die(mysql_error());
            while($rows_find_fid = mysql_fetch_row($row_find_fid)){
            	$rever_fid=$rows_find_fid[0];
            }		
			$sql = "DELETE FROM friendlist WHERE fid ='$rever_fid'";
			mysql_query($sql, $link);	
			header("location:../views/index.php");		        	
        }
        function addGroup($whoami, $id, $groupName){
                require('../host_config.php');
                require_once('../Model/MySQL.php');
                $mysql = new MySQL();
                $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
                $whoami = mysql_real_escape_string($whoami);
                $id = mysql_real_escape_string($id);
                $groupName = mysql_real_escape_string($groupName);
                $sql_max = "SELECT group_id, group_name FROM friendlist WHERE owner_id = '$whoami' and friend_id = 0 ORDER BY group_id ASC";
                $row_max = mysql_query($sql_max, $link) or die(mysql_error());
                $sql_findgroup = "SELECT group_id FROM friendlist WHERE owner_id = '$whoami' and friend_id = 0 and group_name = '$groupName'";
                $row_findgorup = mysql_query($sql_findgroup, $link) or die(mysql_error());
                $checkgID=NULL;
                $group_id = NULL;
                while($result_max=mysql_fetch_row($row_max)){	//找資料中GroupID最大的
                        $group_id=$result_max[0];
                        $group_name=$result_max[1];
                }
                while($result_findgroup = mysql_fetch_row($row_findgorup)){	//找是否有一樣名稱的群組
                        $checkgID=$result_findgroup[0];
                }
                if($checkgID!=NULL){
                }else{
                        //判斷是否有groupid，若有，則以最大的數值加一，以及名稱是否一樣。           
                        if($group_id==NULL){
                                $group_id=1;
                                $group_name=$groupName;
                                
                        }elseif($groupName==$group_name){
                        	
                        }else{
                                $group_id=$group_id+1;
                                $group_name=$groupName;
                        }
                        $sql = "INSERT INTO `friendlist`(`owner_id` ,`friend_id` ,`group_id` ,`group_name` ,`Ischeck`) VALUES ('$whoami', '$id', '$group_id', '$groupName', 1)";
                        mysql_query($sql, $link);
                }
                header("location:../views/index.php");
                return $group_id;                       
        }
        function change_grp($fid,$grpid,$grpname){
        	require('../host_config.php');
        	require_once('../Model/MySQL.php');
        	$mysql = new MySQL();
			$link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
			$fid = mysql_real_escape_string($fid);
			$grpid = mysql_real_escape_string($grpid);
			$grpname = mysql_real_escape_string($grpname);
			$sql_update = "UPDATE  `facetech`.`friendlist` SET  `group_id` =  '$grpid', `group_name` = '$grpname' WHERE  `friendlist`.`fid` = '$fid'";
			mysql_query($sql_update, $link);
			header("location:../views/index.php");
        }
        function edit_grp($uid, $grpid, $groupName){
        	require('../../host_config.php');
            require_once('../../Model/MySQL.php');
            $mysql = new MySQL();
            $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
            $uid = mysql_real_escape_string($uid);
            $grpid = mysql_real_escape_string($grpid);
            $groupName = mysql_real_escape_string($groupName);
            $sql_check = "SELECT group_name from friendlist where `friendlist`.`owner_id` = '$uid'";
            $row_check = mysql_query($sql_check, $link) or die(mysql_error());              
            while($rows_check=mysql_fetch_row($row_check)){
            	if($groupName==$rows_check[0]){		//Check if duplicate
            		header("location:../index.php");
            		exit;
            	}
            }
            if($groupName==$rows_check[0]){		//Check if duplicate
            }else{
            	echo 'no duplicate';
            	$sql = "UPDATE  `facetech`.`friendlist` SET  `group_name` = '$groupName' WHERE  `friendlist`.`owner_id` = '$uid' and group_id = '$grpid'";
            	mysql_query($sql, $link);
            }
			header("location:../index.php");        	
        }
        function delGrp($ownid,$grpid,$grpname){
        	require('../host_config.php');
            require_once('../Model/MySQL.php');
            $mysql = new MySQL();
            $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
            $ownid = mysql_real_escape_string($ownid);
            $grpid = mysql_real_escape_string($grpid);
            $grpname = mysql_real_escape_string($grpname);
            $count="";
            $group="";
            //Delete Group
			if($grpid==""&&$grpname!=""){//only has a grpname
				$sql_count = "SELECT COUNT(fid) FROM friendlist WHERE owner_id = '$ownid' and group_name = '$grpname' GROUP BY owner_id, group_name";
	            $row_count = mysql_query($sql_count, $link);
	            while($rows_count = mysql_fetch_row($row_count)){
	            	$count = $rows_count[0];
	            }				
				$sql_delgrp = "DELETE FROM friendlist WHERE owner_id = '$ownid' and friend_id = 0 and group_name = '$grpname'";
			}elseif($grpname==""&&$grpid!==""){// only has a grpid
				$sql_count = "SELECT COUNT(fid) FROM friendlist WHERE owner_id = '$ownid' and group_id = '$grpid' GROUP BY owner_id, group_id";
	            $row_count = mysql_query($sql_count, $link);
	            while($rows_count = mysql_fetch_row($row_count)){
	            	$count = $rows_count[0];
	            }				
				$sql_delgrp = "DELETE FROM friendlist WHERE owner_id = '$ownid' and friend_id = 0 and group_id = '$grpid'";
			}
			mysql_query($sql_delgrp, $link); // Start Delete A Group
			if($count>1){ //代表有user，將User移到Default
				if($grpid==""){//only has a grpname
					$sql_find = "SELECT fid FROM friendlist WHERE owner_id = '$ownid' and group_name = '$grpname' ORDER BY fid ASC";	
				}elseif($grpname==""){// only has a grpid
					$sql_find = "SELECT fid FROM friendlist WHERE owner_id = '$ownid' and group_id = '$grpid' ORDER BY fid ASC";
				}
				$row_find = mysql_query($sql_find,$link);
				$gid = MakeFriend_Controller::addGroup($ownid, 0, 'Default');
				while($rows_find = mysql_fetch_row($row_find)){
					MakeFriend_Controller::change_grp($rows_find[0],$gid,'Default');
				}		
			}
			header("location:../views/index.php");        			
        }       
        function confirm_request($fid,$whoami,$friendid){
                require('../host_config.php');
                require_once('../Model/MySQL.php');
                $groupName = 'Default';
                $mysql = new MySQL();
                $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
                $fid = mysql_real_escape_string($fid);
                $whoami = mysql_real_escape_string($whoami);
                $friendid = mysql_real_escape_string($friendid);
                $sql_max = "SELECT group_id, group_name FROM friendlist WHERE owner_id = '$whoami' ORDER BY group_id ASC";
                $row_max = mysql_query($sql_max, $link) or die(mysql_error());
                $sql_findgroup = "SELECT group_id FROM friendlist WHERE owner_id = '$whoami' and group_name = '$groupName'";
                $row_findgorup = mysql_query($sql_findgroup, $link) or die(mysql_error());              
                while($result_max=mysql_fetch_row($row_max)){
                        $group_id=$result_max[0];
                        $group_name=$result_max[1];
                }       
                while($result_findgroup = mysql_fetch_row($row_findgorup)){
                        $checkgID=$result_findgroup[0];
                }
                if($group_id==NULL){
                        $group_id=1;
                        $group_name=$groupName;
                }elseif($groupName==$group_name){
                }else{
                        $group_id=$group_id+1;
                        $group_name=$groupName;
                }               
                //Update ischeck
                $sql = "UPDATE  `facetech`.`friendlist` SET  `Ischeck` =  '1' WHERE  `friendlist`.`fid` = '$fid'";
                $mysql->query($sql, $link);
                //新增反向朋友關係
                $sql = "INSERT INTO `friendlist`(`owner_id` ,`friend_id` ,`group_id` ,`group_name` ,`Ischeck`) VALUES ('$whoami', '$friendid', '$group_id', '$groupName', 1)";
                mysql_query($sql, $link);                             
                if($checkgID!=NULL){
                }else{                                  
                        //建立一個反向群組
                        $sql = "INSERT INTO `friendlist`(`owner_id` ,`friend_id` ,`group_id` ,`group_name` ,`Ischeck`) VALUES ('$whoami', 0, '$group_id', '$groupName', 1)";
                        mysql_query($sql, $link);               
                }             
                header("location:../views/friends/requests.php");               
        }       
        function delete_request($fid){
                require('../host_config.php');
                require_once('../Model/MySQL.php');
                $mysql = new MySQL();
                $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
                $fid = mysql_real_escape_string($fid);
                $sql = "DELETE FROM friendlist WHERE fid = '$fid' and Ischeck = 0";
                $mysql->query($sql, $link);
                header("location:../views/friends/requests.php");       
        }       
        function showRequest($whoami){
                require('../../host_config.php');
                require_once('../../Model/MySQL.php');
                $mysql = new MySQL();
                $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
                $whoami = mysql_real_escape_string($whoami);
                $sql = "SELECT user.uid, user.name, user.pic, friendlist.fid, friendlist.owner_id FROM user INNER JOIN friendlist ON user.uid = friendlist.owner_id WHERE friendlist.friend_id='$whoami' and Ischeck = 0 ORDER BY fid ASC";
                $row = mysql_query($sql, $link);
                while($rows=mysql_fetch_row($row)){
                                echo '<div class="media">';
                                        echo '<div class="pull-right">';
                                                //好友確認
                                                echo '<h4><a href="../../Controller/makefriend_controller.php?action=confirmRequest&fid='.$rows[3].'&ownid='.$whoami.'&friendid='.$rows[4].'">好友確認</a><br/></h4>';
                                                //好友忽略
                                                echo '<h4><a href="../../Controller/makefriend_controller.php?action=deleteRequest&fid='.$rows[3].'">好友忽略</a><br/></h4>';
                                        echo '</div>';
                                        echo '<a class="pull-left" href=""><img class="media-object" src="../../'.$rows[2].'" width="64" height="64"></a>';
                                        echo '<div class="media-body">';
                                                echo '<h4>'.$rows[1].'</h4>';
                                        echo '</div>';
                                echo '</div>';  
                }
        }
        function showList($whoami,$id) {
                require('../host_config.php');
                require_once('../Model/MySQL.php');
                $mysql = new MySQL();
                $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
                $whoami = mysql_real_escape_string($whoami);
                $id = mysql_real_escape_string($id);
                $sql_grp = "SELECT group_id, group_name FROM friendlist WHERE owner_id='$id' and friend_id = 0 and Ischeck = 1 ORDER BY group_name ASC";
                $row_grp = mysql_query($sql_grp, $link);                      
                while($rows_grp=mysql_fetch_row($row_grp)){  
                	//Friendlist Group 
                	if($whoami==$id){
                        echo '<div class="pull-right">';
                        //Edit Group 
                           	echo '<a href="#editGroup'.$rows_grp[0].'" data-toggle="modal"><i class="icon-wrench" style="margin-top: 4px"></i></a>';
                        //Delete Group
                            echo '<a  onClick="return confirm(\'Are you sure?\');" href="../Controller/makefriend_controller.php?action=delGrp&id='.$whoami.'&grpid='.$rows_grp[0].'"><i class="icon-remove" style="margin-top: 4px"></i></a><br/>';
						//Edit Group Start//                            
							echo '<div class="pull-right">';
								echo '<div id="editGroup'.$rows_grp[0].'" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
								  echo '<div class="modal-header">';
								    echo '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>';
								    echo '<h3 id="myModalLabel">Edit Group</h3>';
								  echo '</div>';
								  echo '<div class="modal-body">';
									echo '<form class="navbar-form pull-left" action="./friends/edit_group.php" method="post" id="editgroupForm'.$rows_grp[0].'">';
									  	echo '<input type="hidden" name="grpid" value="'.$rows_grp[0].'"/>';
									  	echo 'Type a GroupName：<input type="text" class="span7" name="groupName"><br/>';									
									echo '</form>';
								  echo '</div>';
								  echo '<div class="modal-footer">';
								    echo '<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>';
								    echo '<button class="btn btn-primary" form="editgroupForm'.$rows_grp[0].'">Edit</button>';
								  echo '</div>';
								echo '</div>';										              		
			              	echo '</div>';  
			           	//Edit Group End//     	                            
                        echo '</div>';
                	}
                        echo '<li>&nbsp&nbsp'.$rows_grp[1].'</li>';
                        $sql_user = "SELECT user.uid, user.name, friendlist.fid FROM user INNER JOIN friendlist ON user.uid = friendlist.friend_id WHERE friendlist.owner_id='$id' and friendlist.group_id = '$rows_grp[0]' and friendlist.Ischeck = 1 ORDER BY fid ASC";
                        $row_user = mysql_query($sql_user, $link);                                      
                        while($rows_user=mysql_fetch_row($row_user)){
							$sql_listgrp = "SELECT group_id, group_name FROM friendlist WHERE owner_id='$id' and friend_id = 0 and Ischeck = 1";
							$row_listgrp = mysql_query($sql_listgrp, $link);
							//好友後方的群組選單
									echo '<li class="dropdown pull-right">';
										echo '<a class="dropdown-toggle" data-toggle="dropdown" href="#">';
											echo $rows_grp[1];
											echo '<b class="caret"></b>';
										echo '</a>';
									if($whoami==$id){
										echo '<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">';
										while($rows_listgrp=mysql_fetch_row($row_listgrp)){
											echo '<li><a href="../Controller/makefriend_controller.php?action=changeGroup&fid='.$rows_user[2].'&grpid='.$rows_listgrp[0].'&grpname='.$rows_listgrp[1].'">'.$rows_listgrp[1].'</a></li>';
										}
										echo '</ul>';
									}
									echo '</li >';
									//好友                   	           
                                        echo '<li>&nbsp&nbsp&nbsp&nbsp';
                                    if($whoami==$id){
                                        echo '<a onClick="return confirm(\'Are you sure?\');" href="../Controller/makefriend_controller.php?action=deleteFriend&fid='.$rows_user[2].'&ownid='.$id.'&friendid='.$rows_user[0].'"><i class="icon-remove" style="margin-top: 3px"></i></a>';
                                    }
                                        echo '<a href="index.php?id='.$rows_user[0].'" target="_blank">'.$rows_user[1].'</a></li>';
                        }
                        echo '<li> <li/>';
                }
        }       
        function showGroup($whoami){
                require('../host_config.php');
                require_once('../Model/MySQL.php');
                $mysql = new MySQL();
                $link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
                $whoami = mysql_real_escape_string($whoami);
                $sql = "SELECT DISTINCT group_id, group_name FROM  friendlist where owner_id = '$whoami' ORDER BY group_name ASC";
                $row = mysql_query($sql, $link) or die(mysql_error());
                while($rows=mysql_fetch_row($row)){
                        echo '<option>'.$rows[1].'</option>';
                }               
        }
}
?>